package com.meaningful.design_pattern.chain_of_responsibility.validation;

import com.meaningful.design_pattern.chain_of_responsibility.Length;
import com.meaningful.design_pattern.chain_of_responsibility.Max;
import com.meaningful.design_pattern.chain_of_responsibility.Min;

import java.lang.reflect.Field;
import java.util.Objects;

public class Validator {

    void validate(Object bean) throws Exception {
        Class<?> beanClass = bean.getClass();

        for (Field field : beanClass.getDeclaredFields()) {
            // 遍历每个field的时候应该查看都哪些校验需要校验，组成对应的校验链
            field.setAccessible(true);
            ValidatorChain chain = buildValidateChain(field);
            chain.validate(field.get(bean));
        }

    }

    private ValidatorChain buildValidateChain(Field field) {
        ValidatorChain chain = new ValidatorChain();

        Max max = field.getAnnotation(Max.class);
        if (Objects.nonNull(max)) {
            chain.addLastHandler(new MaxValidatorHandler(max.value()));
        }

        Min min = field.getAnnotation(Min.class);
        if (Objects.nonNull(min)) {
            chain.addLastHandler(new MinValidatorHandler(min.value()));
        }

        Length length = field.getAnnotation(Length.class);
        if (Objects.nonNull(length)) {
            chain.addLastHandler(new LengthValidatorHandler(length.value()));
        }

        return chain;
    }

}
